# 上述声明内容会在#plugin chathook时自动打印

from pymud import PyMudApp, Session, Trigger
from functools import partial
import requests, json

# 插件唯一名称
PLUGIN_NAME = "pku_client"

# 插件有关描述信息
PLUGIN_DESC = {
    "VERSION": "1.0.0",
    "AUTHOR": "spirytus",
    "RELEASE_DATE": "2024-03-22",
    "DESCRIPTION": "将站点内信息发送到客户端中"
}

TRIGGER_DEFINES = [
    {
        "name":"client_fullme",
        "ptn":r"^http://fullme.pkuxkx.net/robot.php.+$",
        "channel":"fullme"
    }
]

def ontri_chat(session:Session, channel, name, line, wildcards):
    data = {channel:line}
    msg = json.dumps(data, ensure_ascii=False)

    if not hasattr(session,"pku_service"):
        session.info("pku service has not init")
        return
    
    if "msg" not in session.pku_service:
        session.info("pku service: msg, has not init")
        return
    
    if not hasattr(session,"pku_plug_data"):
        session.info("pku plug data has not init")
        return
    
    session.pku_plug_data["capture"] = None
    session.pku_service["msg"].send_mud(msg)


def PLUGIN_PYMUD_START(app: PyMudApp):
    "PYMUD自动读取并加载插件时自动调用的函数,  app为APP本体。该函数仅会在程序运行时, 自动加载一次"
    app.set_status(f"插件{PLUGIN_NAME}已加载!")


def PLUGIN_SESSION_CREATE(session: Session):
    "在会话中加载插件时自动调用的函数,  session为加载插件的会话。该函数在每一个会话创建时均被自动加载一次"
    # 为确保插件的触发器不影响自己的脚本也不被自己的脚本影响, 建议将keepEval设置为True, priority设置为小于100
    for tri_define in TRIGGER_DEFINES:
        name = tri_define["name"]
        ptn = tri_define["ptn"]
        channel = tri_define["channel"]

        tri = Trigger(session,
                      id=name,
                      patterns=ptn,
                      group=PLUGIN_NAME,
                      onSuccess=partial(ontri_chat, session, channel),
                      keepEval=True,
                      priority=80)
        session.addTrigger(tri)
        session.info(f"插件{PLUGIN_NAME}已被本会话加载, 已成功向本会话中添加触发器 {name} !!!")


def PLUGIN_SESSION_DESTROY(session: Session):
    "在会话中卸载插件时自动调用的函数,  session为卸载插件的会话。卸载在每一个会话关闭时均被自动运行一次。"
    for tri_define in TRIGGER_DEFINES:
        name = tri_define["name"]
        session.delTrigger(session.tris[name])